﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using PF=Phone.Framework;
using CetWin.Phone.Entity;
using System.Collections.ObjectModel;
using Phone.Framework.Data;
using System.Threading;
using Caliburn.Micro;
using Microsoft.Phone.Shell;
using System.Linq;
using Phone.Framework.Collections;
using Phone.Framework.Threads;
using System.Collections;
using System.Collections.Generic;
using Phone.Framework.CaliburnExtensions.Results;
using CetWin.Phone.Services;
using Phone.Framework;

namespace CetWin.ViewModels
{

    public class HistoriesViewModel : Screen
    {
        private readonly INavigationService navigationService;
        private readonly HistoryService _historyService;
        private readonly CategoryService _categoryService;
        private readonly WordService _wordService;

        public HistoriesViewModel(INavigationService navigationService)
        {
            this.navigationService = navigationService;
            _historyService = IoC.Get<HistoryService>();
            _categoryService = IoC.Get<CategoryService>();
            _wordService = IoC.Get<WordService>();
        }

        protected override void OnInitialize()
        {
            ReFlesh(0);
            ReFlesh(1);
            if (_historyService.Count() == 0)
            {
                _canClear = false;
                NotifyOfPropertyChange(() => CanClear);
            }
            base.OnInitialize();
        }

        #region property

        private Favorite _selectedItem;

        public Favorite SelectedItem
        {
            get { return _selectedItem; }
            set
            {
                _selectedItem = value;
                NotifyOfPropertyChange("SelectedItem");
            }
        }

        private IEnumerable _favorites;

        public IEnumerable Favorites
        {
            get { return _favorites; }
            set
            {
                _favorites = value;
                NotifyOfPropertyChange("Favorites");
            }
        }


        private History _selectedHistoryItem;

        public History SelectedHistoryItem
        {
            get { return _selectedHistoryItem; }
            set
            {
                _selectedHistoryItem = value;
                NotifyOfPropertyChange("SelectedHistoryItem");
            }
        }

        private IEnumerable _histories;

        public IEnumerable Histories
        {
            get { return _histories; }
            set
            {
                _histories = value;
                NotifyOfPropertyChange("Histories");
            }
        }

        #endregion


        public void ChangePivot(int index)
        {
            UIThread.Invoke(() =>
            {
                ThreadManager.Instance.AddTask(() =>
                {
                    if (SelectedPivotIndex == 0)
                    {
                        _canClear = _historyService.Count() > 0;
                    }
                    if (SelectedPivotIndex == 1)
                    {
                        _canClear = _historyService.SearchRecordsCount() > 0;
                    }
                    UIThread.Invoke(() =>
                    {
                        NotifyOfPropertyChange(() => CanClear);
                    });
                });
            });
        }

        private int _selectedPivotIndex;

        public int SelectedPivotIndex
        {
            get { return _selectedPivotIndex; }
            set
            {
                _selectedPivotIndex = value;
                NotifyOfPropertyChange(() => SelectedPivotIndex);
            }
        }

        #region method

        private bool _canClear=true;
        public bool CanClear
        {
            get
            {
                return _canClear;
            }
        }

        public void PlayVoice()
        {
            var db=CetWinDbDataContext.GetDataContext();
            var c = from history in db.Favorites
                    from word in db.Words
                    where history.Name == word.Name
                    orderby history.Time descending
                    select word.Audio;
            
            IoC.Get<IMediaPlayService>().Play(c.ToArray(),0);

        }

        public IEnumerable<IResult> Clear()
        {
            return ResultHelper.ClearAction((IActionResult result) =>
            {
                if (SelectedPivotIndex == 0)
                {
                    _historyService.Clear();
                    ReFlesh(0);
                }
                else
                {
                    _historyService.ClearSearchRecords();
                    ReFlesh(1);
                }
                result.Set();
            });
        }



        public void OpenWordDetailView()
        {
            if (SelectedPivotIndex == 0 && SelectedItem == null) return;
            if (SelectedPivotIndex == 1 && SelectedHistoryItem == null) return;

            var name = string.Empty;
            if (SelectedPivotIndex == 0)
            {
                name = SelectedItem.Name;
            } else if (SelectedPivotIndex == 1)
            {
                name =SelectedHistoryItem.Name;
            }
           
            ThreadManager.Instance.AddTask(() =>
            {
                var word = _wordService.GetWord(name);
                UIThread.Invoke(() =>
                {
                    PhoneStateManager.SetAppState(GlobalConstant.SelectedWordField, word);
                    navigationService.UriFor<WordDetailViewModel>().
                        WithParam(x => x.SearchText, name)
                        .Navigate();
                });
            });
        }

        public IEnumerable<IResult> RememberWord(Favorite selectedItem)
        {
            return ResultHelper.ContextMenuAction((IActionResult result) =>
            {
                ThreadManager.Instance.AddTask(() =>
                {
                    _categoryService.AddTodayWord(selectedItem);
                    ReFlesh(0);
                    result.Set();
                });
            });
        }

        public IEnumerable<IResult> DeleteHistory(Favorite selectedItem)
        {
            return ResultHelper.ContextMenuAction((IActionResult result) =>
            {
                ThreadManager.Instance.AddTask(() =>
                {
                    _historyService.DeleteHistory(selectedItem);
                    ReFlesh(0);
                    result.Set();
                });
            });
        }

        private void ReFlesh(int index)
        {
            ThreadManager.Instance.AddTask(() =>
            {
                if (index == 0)
                {
                    var histories = _historyService.GetGroupHistory();
                    UIThread.Invoke(() =>
                    {
                        Favorites = histories;
                    });
                }
                else if (index == 1)
                {
                    var records = _historyService.GetSearchRecords();

                    UIThread.Invoke(() =>
                    {
                        Histories = records;
                    });
                }
            });
        }

        #endregion
    }
}